package com.itheima.health.controller;

import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Order;
import com.itheima.health.service.OrderService;
import com.itheima.health.utils.resources.MessageConstant;
import com.itheima.health.utils.resources.RedisMessageConstant;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@Api(value = "预约订单")
public class OrderMobileController {
    @Reference
    private OrderService orderService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/order/add")
    @ApiOperation(value = "新增预约订单的方法",notes = "新增预约订单")
    public Result submitOrder(@RequestBody Map map){
        try{
            String verificationCode =(String) map.get("validateCode");
            String key = RedisMessageConstant.SENDTYPE_ORDER+map.get("telephone");
            String redisCode = (String) redisTemplate.opsForValue().get(key);
            String validateCode = (String) map.get("validateCode");
            if(redisCode==null){
                return new Result(false,MessageConstant.SEND_VALIDATECODE_TIMEOUT);
            }else if(redisCode.equals(validateCode)){
                Order order = orderService.add(map);
                return new Result(true, MessageConstant.ADD_ORDER_SUCCESS,order);
            }else {
                return new Result(false,MessageConstant.VALIDATECODE_ERROR);
            }
        }catch (Exception e){
            return new Result(false,e.getMessage());
        }
    }

    @GetMapping("order/sendVerificationCode/{telephone}")
    @ApiOperation(value = "发送验证码的方法",notes = "发送验证码")
    public Result sendVerificationCode(@PathVariable("telephone")String telephone){
        try{
            orderService.sendVerificationCode(telephone);
            return new Result(true,MessageConstant.SEND_VALIDATECODE_SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.SEND_VALIDATECODE_FAIL);
        }
    }

    @GetMapping("order/successOrder/{id}")
    @ApiOperation(value = "预约成功的方法",notes = "预约成功后回显部分信息")
    public Result successOrder(@PathVariable("id")int id){
        System.out.println("===============================");
        Map map = orderService.successOrder(id);
        return new Result(true, MessageConstant.ADD_ORDER_SUCCESS,map);
    }
}
